# 作者: 王道 龙哥
# 2024年06月14日11时00分53秒
# dartou@qq.com
a = [5, 2, 3, 1, 4]
# a.sort() #函数返回None
# print(a)
print(sorted(a))

sorted({1: 'D', 2: 'B', 3: 'B', 5: 'E', 4: 'A'})

word_list = "This is a test string from Andrew".split()


def my_sort_key(word):
    """
    自定义的比较规则
    :param word:
    :return:
    """
    return word.lower()


print(sorted(word_list, key=my_sort_key))
print('-' * 50)
# alt+shift 竖选
student_tuples = [
    ('jane', 'B', 12),
    ('john', 'A', 15),
    ('dave', 'B', 10),
]

# 匿名函数只用一次，阅读效率比较高   用完即销毁

print(sorted(student_tuples, key=lambda x: x[2]))

print(f'排序对象--------------------')


class Student:

    def __init__(self, name, grade, age):
        self.name = name
        self.grade = grade
        self.age = age

    def __repr__(self):
        return repr((self.name, self.grade, self.age))  # 以 元组 形式输出


student_objects = [
    Student('jane', 'A', 15),
    Student('john', 'B', 12),
    Student('dave', 'B', 10),
]
print(sorted(student_objects, key=lambda student: student.age))

from operator import itemgetter, attrgetter

# print(sorted(student_tuples, key=itemgetter(2)))
# print(sorted(student_objects, key=attrgetter('age')))
print(f'多级排序')
print(sorted(student_tuples, key=itemgetter(1, 2)))
print(sorted(student_objects, key=attrgetter('grade', 'age')))

print('排序的稳定性')
data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)]
print(sorted(data, key=itemgetter(0)))

print('字典中混合list排序')
mydict = {'Li': ['M', 7],
          'Zhang': ['E', 2],
          'Wang': ['P', 3],
          'Du': ['C', 2],
          'Ma': ['C', 9],
          'Zhe': ['H', 7]}

print(sorted(mydict.items(), key=lambda x: x[1][1]))

print('列表中是字典排序')
game_result = [
    {"name": "Bob", "wins": 10, "losses": 3, "rating": 75.00},
    {"name": "David", "wins": 3, "losses": 5, "rating": 57.00},
    {"name": "Carol", "wins": 4, "losses": 5, "rating": 57.00},
    {"name": "Patty", "wins": 9, "losses": 3, "rating": 71.48}]

print(sorted(game_result, key=itemgetter('rating', 'wins')))
print(sorted(game_result, key=lambda x: (x['rating'], -x['wins'])))

my_tuple = [(3, 5), (1, 2), (2, 4), (3, 1), (1, 3)]
print(sorted(my_tuple, key=lambda x: (x[0], -x[1])))  # x[0] 相等的话 x[1] 降序
